using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Diagnostics;
using Microsoft.Reporting.WinForms;


namespace CustomReportEngine
{
    public partial class ReportViewer : Form
    {
        private SqlDataAdapter da;
        private SqlConnection cn;
        private FNMA_PipelineDataSet ds = new FNMA_PipelineDataSet();

        public ReportViewer()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'FNMA_PipelineDataSet.vwCustomReportView' table. You can move, or remove it, as needed.
			try
			{
				setFilters();
				loadFiltersFromSettings();
				fillDataSet();
				initReport();
			}
			catch (Exception ex)
			{
				Util.ErrorLog.Write("Loading", ex);
			}
        }

        private void initReport()
        {
            try
            {
				reportViewer1.LocalReport.DataSources.Clear();
                if (ds.vwCustomReportView.Rows.Count > 0)
                {
                    // Set the path of the rdlc document
                    string reportPath = "Reports/JimmyMayfield-Report1.rdlc";

					reportViewer1.LocalReport.DataSources.Add(
                        new ReportDataSource("FNMA_PipelineDataSet_vwCustomReportView", ds.vwCustomReportView));
                    List<ReportParameter> parameters = new List<ReportParameter>();
                    parameters.Add(new ReportParameter("ReportName", "Origination Report"));

                    this.reportViewer1.LocalReport.ReportPath = reportPath;
                    this.reportViewer1.LocalReport.SetParameters(parameters);
                }
				this.reportViewer1.RefreshReport();

            }
            catch (Exception ex)
            {
				throw ex;
            }
        }
        private void fillDataSet()
        {
            try
            {
                string strConnection = Util.ConnectionManager.ConnectionString;
                cn = new SqlConnection(strConnection);
                string sql = "SELECT * FROM vwCustomReportView WHERE deal_app_received > '{0}' "+
                    " AND deal_app_received < '{1}' AND {2} AND {3} AND {4}";
                string[] sqlParams = new string[5];
                sqlParams[0] = dtFrom.Value.ToShortDateString();
                sqlParams[1] = dtTo.Value.ToShortDateString();
                sqlParams[2] = "1=1";

                if (lbDealTypes.SelectedItems.Count > 0)
                {
                    StringBuilder temp = new StringBuilder("deal_type IN (");
                    for (int i = 0; i < lbDealTypes.SelectedItems.Count; i++ )
                    {
                        temp.Append("'" + ((Util.ComboBoxItem)lbDealTypes.SelectedItems[i]).Value + "'");
                        if (i < lbDealTypes.SelectedItems.Count - 1)
                            temp.Append(", ");
                    }
                    temp.Append(")");
                    sqlParams[2] = temp.ToString();
                }

                sqlParams[3] = "1=1";

                if (lbStatuses.SelectedItems.Count > 0)
                {
                    StringBuilder temp = new StringBuilder("deal_status IN (");
                    for (int i = 0; i < lbStatuses.SelectedItems.Count; i++)
                    {
                        temp.Append(((Util.ComboBoxItem)lbStatuses.SelectedItems[i]).Value);
                        if (i < lbStatuses.SelectedItems.Count - 1)
                            temp.Append(", ");
                    }
                    temp.Append(")");
                    sqlParams[3] = temp.ToString();
                }

				sqlParams[4] = "1=1";

				if (lbDealSubType.SelectedItems.Count > 0)
				{
					StringBuilder temp = new StringBuilder("deal_sub_type2 IN (");
					for (int i = 0; i < lbDealSubType.SelectedItems.Count; i++)
					{
						temp.Append("'" + ((Util.ComboBoxItem)lbDealSubType.SelectedItems[i]).Value + "'");
						if (i < lbDealSubType.SelectedItems.Count - 1)
							temp.Append(", ");
					}
					temp.Append(")");
					sqlParams[4] = temp.ToString();
				}
                sql = String.Format(sql, sqlParams);
                da = new SqlDataAdapter(sql, cn);
				ds.Clear();
                da.Fill(ds, "vwCustomReportView");
                this.txtDebug.Text = "Loaded " + ds.vwCustomReportView.Rows.Count + " deals.";
            }
            catch (Exception ex)
            {
				throw ex;
            }
            finally
            {
                if (cn != null &&
                    cn.State != ConnectionState.Closed)
                    cn.Close();
            }
        }

        private void setFilters() 
        {
            lbDealTypes.DataSource = Util.ConnectionManager.GetDealTypesList();
            lbStatuses.DataSource = Util.ConnectionManager.GetStatusList();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
			try
			{
				this.txtDebug.Text = "Loading... ";
				fillDataSet();
				initReport();
			}
			catch (Exception ex)
			{
				Util.ErrorLog.Write("Refreshing", ex);
			}
        }

        private void OnClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                Properties.Settings.Default.FilterDateFrom = dtFrom.Value;
                Properties.Settings.Default.FilterDateTo = dtTo.Value;
                StringBuilder dealTypes = new StringBuilder("");
                if (lbDealTypes.SelectedItems.Count > 0)
                {
                    for (int i = 0; i < lbDealTypes.SelectedItems.Count; i++)
                    {
                        dealTypes.Append(((Util.ComboBoxItem)lbDealTypes.SelectedItems[i]).Value);
                        if (i < lbDealTypes.SelectedItems.Count - 1)
                            dealTypes.Append("|");
                    }
                }
                Properties.Settings.Default.FilterDealTypes = dealTypes.ToString();

                StringBuilder statuses = new StringBuilder("");
                if (lbStatuses.SelectedItems.Count > 0)
                {
                    for (int i = 0; i < lbStatuses.SelectedItems.Count; i++)
                    {
                        statuses.Append(((Util.ComboBoxItem)lbStatuses.SelectedItems[i]).Value);
                        if (i < lbStatuses.SelectedItems.Count - 1)
                            statuses.Append("|");
                    }
                }
                Properties.Settings.Default.FilterStatuses = statuses.ToString();
				Properties.Settings.Default.FormState = this.WindowState;
				Properties.Settings.Default.FormSize = this.Size;

                Properties.Settings.Default.Save();
            }
            catch (Exception ex)
            {
				Util.ErrorLog.Write("Closing", ex);
            }
        }

        private void loadFiltersFromSettings()
        {
            try
            {
                dtFrom.Value = (Properties.Settings.Default.FilterDateFrom <= DateTime.MinValue ? 
					DateTime.Now : Properties.Settings.Default.FilterDateFrom);
				dtTo.Value = (Properties.Settings.Default.FilterDateTo <= DateTime.MinValue ?
					DateTime.Now : Properties.Settings.Default.FilterDateTo);
                string[] dealTypes = Properties.Settings.Default.FilterDealTypes.Split('|');
                if (dealTypes.Length > 0)
                {
                    lbDealTypes.SelectedItems.Clear();
                    for (int i = 0; i < dealTypes.Length; i++)
                    {
                        for (int j = 0; j < lbDealTypes.Items.Count; j++)
                        {
                            Util.ComboBoxItem item = (Util.ComboBoxItem)lbDealTypes.Items[j];
                            if (item.Value == dealTypes[i])
                                lbDealTypes.SelectedItems.Add(item);
                        }
                    }
                }
                string[] statuses = Properties.Settings.Default.FilterStatuses.Split('|');
                if (statuses.Length > 0)
                {
                    lbStatuses.SelectedItems.Clear();
                    for (int i = 0; i < statuses.Length; i++)
                    {
                        for (int j = 0; j < lbStatuses.Items.Count; j++)
                        {
                            Util.ComboBoxItem item = (Util.ComboBoxItem)lbStatuses.Items[j];
                            if (item.Value == statuses[i])
                                lbStatuses.SelectedItems.Add(item);
                        }
                    }
                }
				this.Size = Properties.Settings.Default.FormSize;
				this.WindowState = Properties.Settings.Default.FormState;
            }
            catch (Exception ex)
            {
				Util.ErrorLog.Write("Restoring Filters", ex);
            }
        }

		private void lbDealTypes_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (lbDealTypes.SelectedItems.Count == 0)
				lbDealSubType.DataSource = null;
			else
			{
				StringBuilder statuses = new StringBuilder("AND deal_type IN (");
				for (int i = 0; i < lbDealTypes.SelectedItems.Count; i++)
				{
					statuses.Append("'"+((Util.ComboBoxItem)lbDealTypes.SelectedItems[i]).Value+"'");
					if (i < lbDealTypes.SelectedItems.Count - 1)
						statuses.Append(",");
				}
				statuses.Append(")");
				lbDealSubType.DataSource = Util.ConnectionManager.GetDealSubTypesList(statuses.ToString());
                lbDealSubType.SelectedIndex = -1;
			}			
		}
    }
}